package com.xltt.watchclient;

import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.xltt.watchclient.model.ButtonInfo;
import com.xltt.watchclient.module.ScanManager;
import com.xltt.watchclient.module.bean.OptResult;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import static com.xltt.watchclient.module.service.BleController.REQUEST_LIST;

public class ScanFragment extends Fragment {
    List<ButtonInfo> scanList = new ArrayList<>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_scan, container, false);
    }

    ScanManager mScanManager;
    QuickAdapter mScanQuickAdapter;
    RecyclerView mScanRecyclerView;
    View scan_container;
    NavController nNavController;
    View prgLayout;

    private void setupLoading(View view) {
        prgLayout = view.findViewById(R.id.prgLayout);
    }

    public void showLoading() {
        prgLayout.setVisibility(View.VISIBLE);
    }

    public void hideLoading() {
        prgLayout.setVisibility(View.GONE);
    }

    private static void unpairDevice(BluetoothDevice device) {
        try {
            LogTool.d("unpairDevice");
            Method m = device.getClass()
                    .getMethod("removeBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
        } catch (Exception e) {
            LogTool.d(e.getMessage());
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        requireActivity().setTitle("扫描设备");
        nNavController = Navigation.findNavController(view);
        mScanManager = new ScanManager(requireContext());
        setupLoading(view);
        scan_container = view.findViewById(R.id.scan_container);
        mScanRecyclerView = view.findViewById(R.id.scan_list);
        mScanRecyclerView.setLayoutManager(new GridLayoutManager(requireContext(), 1, LinearLayoutManager.VERTICAL, false));
        mScanQuickAdapter = new QuickAdapter(R.layout.item_button_view, scanList);
        mScanRecyclerView.setAdapter(mScanQuickAdapter);
        mScanQuickAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                ButtonInfo mButtonInfo = scanList.get(position);
                if (mButtonInfo != null) {
                    LogTool.d(mButtonInfo.name);
                    if (nNavController.getPreviousBackStackEntry() != null) {
                        nNavController.getPreviousBackStackEntry()
                                .getSavedStateHandle().set("device", mButtonInfo.data);
                        LogTool.d("开始连接");
                    }
                    nNavController.popBackStack();
                }
            }
        });

    }


    class QuickAdapter extends BaseQuickAdapter<ButtonInfo, BaseViewHolder> {

        public QuickAdapter(int layoutResId, @Nullable List<ButtonInfo> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, ButtonInfo item) {
            helper.setText(R.id.item_title, item.name);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = false, priority = 0)
    public void onResult(OptResult message) {
        switch (message.type) {
            case REQUEST_LIST: {
                scanList.clear();
                if (message.deviceNames != null) {
                    for (Map.Entry<String, String> entry : message.deviceNames.entrySet()) {
                        ButtonInfo mButtonInfo = new ButtonInfo(0, entry.getValue());
                        mButtonInfo.data = entry.getKey();
                        scanList.add(mButtonInfo);
                    }
                }
                mScanQuickAdapter.notifyDataSetChanged();

                break;
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        ((MainActivity)requireActivity()).startScan();
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }
}
